<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="category_tree.js"></script>
<script type="text/javascript" src="assets/js/jquery-1.11.3.min.js"></script>
<script src="assets/js/knockout-3.3.0.js"></script>
</head>

<body>
	<form method="get">
		<div data-bind='foreach: lines'>
			<div>
				<select
					data-bind='options: sampleProductCategories, optionsText: "t", optionsCaption: "选择分类", value: category'>
				</select> <span data-bind="with: category"> <select name="childid"
					data-bind='options: c, optionsText: "t",optionsValue:"id" , optionsCaption: "选择分类"  '>
				</select>
				</span> <span data-bind='click: $parent.removeLine'>移除</span>
			</div>

		</div>

		<button data-bind='click: addLine ,visible: lines().length <3'>添加分类</button>
		<input type="submit" />
	</form>
	<script type="text/javascript">
		function formatCurrency(value) {
			return "$" + value.toFixed(2);
		}
		var CartLine = function() {
			var self = this;
			self.category = ko.observable();
			self.product = ko.observable();
			self.quantity = ko.observable(1);
			self.subtotal = ko.pureComputed(function() {
				return parseInt("0" + self.quantity(), 10);
			});
			// Whenever the category changes, reset the product selection
			self.category.subscribe(function() {
				self.product(undefined);
			});
		};
		var Cart = function() {
			// Stores an array of lines, and from these, can work out the grandTotal
			var self = this;
			self.lines = ko.observableArray([ new CartLine() ]); // Put one line in by default
			self.grandTotal = ko.pureComputed(function() {
				var total = 0;
				$.each(self.lines(), function() {
					total += this.subtotal()
				})
				return total;
			});
			// Operations
			self.addLine = function() {
				self.lines.push(new CartLine())
			};
			self.removeLine = function(line) {
				self.lines.remove(line)
			};
			self.save = function() {
				var dataToSave = $.map(self.lines(), function(line) {
					return line.product() ? {
						productName : line.product().name,
						quantity : line.quantity()
					} : undefined
				});
				alert("Could now send this to server: "
						+ JSON.stringify(dataToSave));
			};
		};
		ko.applyBindings(new Cart());
	</script>

</body>

</html>